var endX;
var startX;
var currentX;
var timerId = 0;
var step = 2;
var $fish;

$(window).load(function() {
	init();
	addHandler();
});

function init() {	
	var $bar = $("#bar");
	$fish = $("#img");
	startX = $bar.position().left;
	endX = $bar.width() + startX - $fish.width();
	currentX = startX;
}

function addHandler() {	
	$("#btnStart").on("click", start);
	$("#btnStop").on("click", stopMove);
}

function start() {	
	if (timerId == 0) timerId = setInterval(startMove, 20);
}

function startMove() {
	currentX += step;
	
	if (currentX > endX) {
		currentX = endX;
		step = -2;
	}
	
	if (currentX < startX) {
		currentX = startX;
		step = 2;
	}
	
	$fish.css("left", currentX);
}

function stopMove() {
	if (timerId != 0) {
		clearInterval(timerId);
		timerId = 0;
	}
}